<template>
  <div class="content">
    <div class="breadcrumb" :gutter="24">
      {{ $t("recipe.process_formula") }}
    </div>
    <div class="device_group_sel">
       <el-form ref="form" :model="formData" label-width="90px" size="small">
          <el-row :gutter="28">
            <el-col :xs="9" :sm="6" :md="5" :lg="5" :xl="4">
              <el-form-item :label="$t('recipe.device_group_sel')" class="selectItem">
                <el-select v-model="formData.trainId" remote filterable :remote-method="remoteMethodGroup" placeholder=""
                  v-el-select-loadmore="loadMoreGroupFun" clearable @clear="clearGroup">
                  <el-option v-for="(item,index) in groupList" :key="index" :label="item.entName" :value="item.fid"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="4" :sm="4" :md="4" :lg="4" :xl="4">
              <el-form-item label-width="0px">
                <el-button type="primary" size="small" @click="handleConfirmGroup()" :disabled="isreadOnly"
                  :loading="loading">{{ $t("run.confirm") }}</el-button>
                  <el-button type="primary" size="small" @click="handleFormula()">{{ $t("recipe.sel_recipe") }}</el-button>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
    </div>
   

    <!-- 选择配方弹窗 -->
    <el-dialog v-dialogDrag :title="$t('recipe.sel_recipe')" :visible.sync="isShowDialog" :close-on-click-modal="false" width="58%"
      class="isShowDialog" :before-close="handleClose">
      <el-form :model="ruleForm" label-width="85px" ref="ruleForm" size="small" :rules="rulesJob" :hide-required-asterisk="true">
        <el-row :gutter="28">
          <el-col :xs="24" :sm="24" :md="10" :lg="10" :xl="10">
            <el-form-item :label="$t('common.keyword')">
              <el-input v-model="ruleForm.keyword" clearable placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="10" :lg="10" :xl="10">
            <el-form-item :label="$t('recipe.state')" label-width="40px" class="w-100">
              <el-select v-model="ruleForm.status" placeholder="" clearable>
                <el-option v-for="(item,index) in statusList" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2">
            <el-form-item label-width="0px">
              <el-button type="primary" size="small" @click="handleSearch">{{ $t("common.query") }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="tableAuto tableAuto1">
        <el-table :data="formulaList" v-loading="formulaLoading" style="left:3% ;width: 95%" height="300px" @row-click="rowFormulaClick"
          :header-cell-style="{background:'#EAEBEC'}" ref="formulaTable" highlight-current-row>
          <el-table-column label="" width="50" align="center">
            <template slot-scope="scope">
              <div>
                <el-radio :label="scope.row.fid" v-model="formulaFid">&nbsp;</el-radio>
              </div>
            </template>
          </el-table-column>
          <el-table-column type="index" :label="$t('common.number')" width="80" align="center">
            <template slot-scope="scope">
              {{table_index1(scope.$index+1)}}
            </template>
          </el-table-column>
          <el-table-column :label="$t('recipe.formula_name')" show-overflow-tooltip prop="recipeName" width="150"></el-table-column>
          <el-table-column :label="$t('common.version')" show-overflow-tooltip prop="version" width="80"></el-table-column>
          <el-table-column :label="$t('recipe.material_code')" show-overflow-tooltip prop="item" width="100"></el-table-column>
          <el-table-column :label="$t('recipe.formula_status')" show-overflow-tooltip prop="item" width="100">
            <template slot-scope="scope">
              {{queryStatus(scope.row.recipeStatus)}}
            </template>
          </el-table-column>
          <el-table-column :label="$t('recipe.formula_description')" show-overflow-tooltip prop="notes"></el-table-column>
        </el-table>

      </div>
      <div class="pagination-area" style="padding:10px 0">
        <el-pagination @size-change="handleSizeChange1" @current-change="handleCurrentChange1" :page-sizes="[10, 20, 50, 100]"
          :page-size="formulaPage.pageSize" :current-page="formulaPage.pageNum" layout="total, sizes, prev, pager, next, jumper"
          :total="formulaPage.total">
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :loading="ruleFormLoading" @click="handleCreate()">{{$t('run.confirm')}}</el-button>
        <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>


    <el-dialog v-dialogDrag :title="title" :visible.sync="isShowAdd" :close-on-click-modal="false"
      :width="screenWidth > 1024 ? '30%' : '60%'" :before-close="handleCloseJob">
      <el-form :model="ruleFormJob" label-width="100px" ref="ruleFormJob" size="small" :rules="rulesJob" :hide-required-asterisk="true">
        <el-row :gutter="24">
          <el-col :xs="24">
            <el-form-item label="单元作业" prop="jobDesc">
              <el-input v-model="ruleFormJob.jobDesc" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('recipe.auto_start')" prop="autoStart" class="w-100">
              <el-select v-model="ruleFormJob.autoStart" placeholder="" clearable>
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('recipe.start_delay')">
              <el-input v-model="ruleFormJob.delayTime" placeholder="" clearable>
                <template slot="append">min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('basic.equipment_type')" prop="initSchedEntId" class="selectClass">
              <el-select v-model="ruleFormJob.initSchedEntId" placeholder="" clearable filterable :remote-method="remoteMethodItemClass"
                v-el-select-loadmore="loadMoreItemClassFun" @clear="clearItemClass" @change="handleDeviceType">
                <el-option v-for="(item,index) in classIdList" :key="index" :label="item.className" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="设备" class="selectClass" prop="equipmentId">
              <el-select v-model="ruleFormJob.equipmentId" filterable placeholder="" clearable @change="handleequipmentId">
                <el-option v-for="(item,index) in equipmentList" :key="index" :label="item.entName" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" v-if="ruleFormJob.finalJob != 1">
            <el-form-item :label="$t('recipe.start_sequence')" prop="seqNo">
              <el-input type="number" v-enterNumber3 v-model="ruleFormJob.seqNo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :loading="zyloading"
          @click="handleConfirm('ruleFormJob')">{{ $t("common.preservation") }}</el-button>
        <el-button @click="handleCloseJob()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>





    <el-dialog v-dialogDrag title="选择作业" :visible.sync="isShowDialogJob" :close-on-click-modal="false" width="58%" class="isShowDialog" :before-close="handleCloseJobDialog">
      <div style="padding:10px 0">
        <el-button type="primary" size="small" :disabled="isreadOnly" @click="handleAdd()">{{ $t("common.add") }}</el-button>
        <el-button type="primary" size="small" :disabled="isreadOnly" @click="handleEdit()">{{ $t("common.edit") }}</el-button>
        <el-button type="primary" size="small" :disabled="isreadOnly" @click="handleDel()">{{ $t("common.remove") }}</el-button>
      </div>
      

      <el-table :data="tableData" v-loading="tableLoading" style="width: 100%" height="300px" @row-click="rowClick"
          :header-cell-style="{background:'#EAEBEC'}" ref="refTable" highlight-current-row row-key="fid">
        <el-table-column label="" width="50" align="center">
          <template slot-scope="scope">
            <div>
              <el-radio :label="scope.row.fid" v-model="radioId">&nbsp;</el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" :label="$t('common.number')" width="80" align="center">
          <template slot-scope="scope">
            {{table_index(scope.$index+1)}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('recipe.assignment_name')" show-overflow-tooltip prop="jobDesc"></el-table-column>
        <el-table-column :label="$t('recipe.define_equipment')" show-overflow-tooltip prop="entName">
          <template slot-scope="scope">
            <span v-if="scope.row.equipmentVo">
              {{scope.row.equipmentVo.entName}}
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('basic.equipment_type')" show-overflow-tooltip prop="className">
          <template slot-scope="scope">
            {{scope.row.equipmentClassVo.className}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('recipe.start_sequence')" show-overflow-tooltip prop="seqNo"></el-table-column>
        <el-table-column :label="$t('recipe.auto_start')" width="100" show-overflow-tooltip prop="autoStart">
          <template slot-scope="scope">
            <span>
              {{scope.row.autoStart == 1 ? '是' : '否'}}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-area">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[20, 30, 50, 100]"
          :page-size="pager.pageSize" :current-page="pager.pageNum" layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleConfirmJob()">{{$t('run.confirm')}}</el-button>
        <el-button @click="handleCloseJobDialog()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>

    <!-- <el-dialog v-dialogDrag title="选择PHASE2" :visible.sync="isShowPhaseDialog" :close-on-click-modal="false" width="30%" class="isShowDialog" :before-close="handleClosePhaseDialog">
      <el-table :data="phaseList" style="width: 100%" height="300px" @row-click="rowClickPhase"
          :header-cell-style="{background:'#EAEBEC'}" ref="refPhaseTable" highlight-current-row row-key="fid">

        <el-table-column label="" width="50" align="center">
          <template slot-scope="scope">
            <div>
              <el-radio :label="scope.row.fid" v-model="phaseRadioId">&nbsp;</el-radio>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="phase名称" show-overflow-tooltip prop="text"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleConfirmPhase()">{{$t('run.confirm')}}</el-button>
        <el-button @click="handleClosePhaseDialog()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog> -->


    <el-dialog v-dialogDrag title="phase名称" :visible.sync="isShowPhaseDialog" :close-on-click-modal="false" width="30%" class="isShowDialog" :before-close="handleClosePhaseDialog">
      <div style="padding-top: 20px;">
        <el-form :model="ruleFormPhase" :rules="rulesPhase" ref="ruleFormPhase" label-width="100px" size="small" class="demo-ruleForm">
          <el-form-item label="phase名称" prop="name">
            <el-input v-model="ruleFormPhase.name"></el-input>
          </el-form-item>
          <el-form-item label="请设备类型" prop="fid"  class="phaseType">
            <el-select v-model="ruleFormPhase.fid" placeholder="设备类型">
            <el-option v-for="item in phaseList" :key="item.fid" :label="item.text" :value="item.fid"></el-option>
          </el-select>
          </el-form-item>
        </el-form>
        </div>
        
      
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" size="small" @click="handleConfirmPhase('ruleForm')">{{$t('run.confirm')}}</el-button>
          <el-button @click="handleClosePhaseDialog()" size="small">{{ $t("common.cancel") }}</el-button>
        </span>
    </el-dialog>



    <div class="box" ref="box">
        <div class="left" :style="{'width':isMxgraphVue2 ? 'calc(50% - 5px)' : '100%'}">
          <!-- :isShowDialogJob.sync="isShowDialogJob"  -->
          <mxgraphVue 
            @isShowDialogJobFn="isShowDialogJobFn"
            @hanfleDouble="hanfleDouble"
            :recipeId="recipeId" 
            :currObjMx="currObjMx" 
            :count="count" 
            @getMxgraphVue2Data="getMxgraphVue2Data"
            :widthVal.sync="widthVal"
            :trainId="formData.trainId"
            :formulaCount="formulaCount"
            @handleSelectedNode="handleSelectedNode"
            :tableData="tableData"
          ></mxgraphVue>
        </div>
          <div class="resize" title="收缩侧边栏" :style="{'width':isMxgraphVue2 ? '10px' : '0%'}">
              ⋮
          </div>
        
        <div class="mid" :style="{'width':isMxgraphVue2 ? 'calc(50% - 5px)' : '0%'}">
          <mxgraphVue2 
            :recipeId="recipeId" 
            :currObjMx="currObjMx"  
            :isMxgraphVue2.sync="isMxgraphVue2"
            :currPhaseObj="currPhaseObj"
            :phaseCount="phaseCount"
            :phaseList="phaseList"
            :equipId="equipId"
            :rightXmlCount="rightXmlCount"
            :isShowPhaseDialog.sync="isShowPhaseDialog"
            @handlePhaseType="handlePhaseType"
            @doubleClickNode="doubleClickNode"
          ></mxgraphVue2>
        </div>
    </div>




    <!-- 阶段配置弹框 -->
    <phATO :isShowATO="isShowATO" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phATO> <!-- 全自动 -->
    <phBTN :isShowBTN="isShowBTN" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phBTN> <!-- 全手动 -->
    <phDATA :isShowDATA="isShowDATA" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phDATA><!-- 数据 -->
    <phADM :isShowADM="isShowADM" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phADM> <!-- 手动加料 -->
    <phCHA1 :isShowCHA="isShowCHA" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phCHA1><!-- 自动加料一-->
    <!-- <phCHA2 :isShowCHA2="isShowCHA2" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData" :stepObj="stepObj"></phCHA2>自动加料二废弃
        <phCHA3 :isShowCHA3="isShowCHA3" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData" :stepObj="stepObj"></phCHA3>自动加料三废弃 -->
    <phIPT :isShowIPT="isShowIPT" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phIPT><!-- 数据录入 -->
    <phAGI :isShowAGI="isShowAGI" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phAGI><!-- 搅拌控制 -->
    <phTEM :isShowTEM="isShowTEM" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phTEM><!-- 温度控制 -->
    <phGAS :isShowIFO="isShowIFO" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phGAS><!-- 信息提示 -->
    <phTHR :isShowOTM="isShowOTM" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phTHR><!-- 物料产出 -->
    <phEXC :isShowEXC="isShowEXC" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phEXC><!-- 接收罐气体置换 -->
    <phREC :isShowREC="isShowREC" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phREC><!-- 冷凝接受 -->
    <phTRS1 :isShowTRS="isShowTRS" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phTRS1><!-- 转料一 -->
    <!-- <phTRS2 :isShowTRS2="isShowTRS2" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData" :stepObj="stepObj"></phTRS2>转料二废弃 -->
    <phDATATEM1 :isShowTEMWD1="isShowTEMWD1" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phDATATEM1><!-- 温度配置一 -->
    <phDATATEM2 :isShowTEMWD2="isShowTEMWD2" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phDATATEM2><!-- 温度配置二 -->
    <phDATAPRE :isShowPRE="isShowPRE" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj"></phDATAPRE><!-- 温度压力 -->
    <phJUMP :isShowJUMP="isShowJUMP" :isreadOnly="isreadOnly" @closePH="closePH" @uptionData="uptionData"
      :stepObj="stepObj" :equipId="equipId"></phJUMP><!-- 温度压力 -->
    
  

  </div>
</template>


<script>
import { scheduling } from "@/api/scheduling"
import { configure } from "@/api/configure"
import { addFormula } from "@/api/addFormula"
import { formula } from "@/api/formula"
import { child } from "@/utlis/phaseData.js"
import mxgraphVue from './maxgraph1/customToolbar/customToolbar.vue'
// import mxgraphVue3 from './mxgraph/mxgraph.vue'
import mxgraphVue2 from './maxgraph2/customToolbar/customToolbar.vue'
import Index from '../../../components/particles/index.vue'
import phATO from "./template/phAto.vue";
import phBTN from "./template/phBtn.vue"
import phDATA from "./template/phData.vue";
import phADM from "./template/phAdm.vue";
import phCHA1 from "./template/phCha1.vue";
// import phCHA2 from "./template/phCha2.vue";
// import phCHA3 from "./template/phCha3.vue";
import phIPT from "./template/phIpt.vue";
import phAGI from "./template/phAgi.vue";
import phTEM from "./template/phTem.vue";
import phGAS from "./template/phGas.vue";
import phTHR from "./template/phThr.vue";
import phEXC from "./template/phExc.vue";
import phREC from "./template/phRec.vue";
import phTRS1 from "./template/phTrs1.vue";
// import phTRS2 from "./template/phTrs2.vue";
import phDATATEM1 from "./template/phDataTem1.vue";
import phDATATEM2 from "./template/phDataTem2.vue";
import phDATAPRE from "./template/phDataPre.vue";
import phJUMP from "./template/phJump.vue";

export default {
  components:{
    mxgraphVue,
    mxgraphVue2,
    Index,
    phATO,
    phBTN,
    phDATA,
    phADM,
    phCHA1,
    // phCHA2,
    // phCHA3,
    phIPT,
    phAGI,
    phTEM,
    phGAS,
    phTHR,
    phEXC,
    phREC,
    phTRS1,
    // phTRS2,
    phDATATEM1,
    phDATATEM2,
    phDATAPRE,
    phJUMP,
  },
  data(){
    let seqNoFn = (rule, value, callback) => {
      if (this.tableData.length > 0 && !value && this.ruleFormJob.finalJob != 1) {
        callback(new Error('启动顺序不能为空'));
      } else {
        callback();
      }
    }
    let nextJobFn = (rule, value, callback) => {
      if (this.ruleFormJob.finalJob != 1) {
        if (!value) {
          callback(new Error('下个设备类型不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    return {
      child: child,
      groupList: [],
      formData: {
        trainId: ""
      },
      process:"",
      formulaFid: "",
      ruleFormJob: {
        jobDesc: "",
        initSchedEntId: "",
        seqNo: "",
        nextJob: "",
        equipmentId: "",
        firstJob: "",
        finalJob: "",
        autoStart: 0,
        delayTime: 0,
      },
      pageGroud: {
        pageNum: 1,
        pageSize: 100,
        keyword: ""
      },
      loading:false,
      isreadOnly: true,
      isShowDialog:false,
      ruleForm: {
        keyword: "",
        status: ""
      },
      rulesJob: {
        jobDesc: [{ required: true, message: '单元作业不能为空', trigger: 'blur' }],
        initSchedEntId: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
        seqNo: [{ validator: seqNoFn, trigger: 'change' }],
        nextJob: [{ validator: nextJobFn, trigger: 'change' }],
        firstJob: [{ required: true, message: '起始作业不能为空', trigger: 'change' }],
        finalJob: [{ required: true, message: '最后作业不能为空', trigger: 'change' }],
      },
      statusList: [{
        label: "编辑",
        value: "1"
      }, {
        label: this.$t('common.examine'),
        value: "2"
      }, {
        label: this.$t('common.approval'),
        value: "3"
      }, {
        label: "启用",
        value: "4"
      }, {
        label: this.$t('common.abandoned'),
        value: "5"
      }, {
        label: "实验",
        value: "6"
      }],
      formulaPage: {
        pageNum: 1,
        pageSize: 10,
        keyword: ""
      },
      pager: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
        field: 'seqNo',
        order: 'asc',
      },
      recipePager: {
        field: 'fCreatorTime',
        order: 'DESC',
      },
      formulaLoading:false,
      formulaList:[],
      isTrainVo: false,
      recipeId:"",
      tableLoading:false,
      ruleFormLoading:false,
      tableData:[],
      classIdList:[],
      screenWidth: document.body.clientWidth,
      isShowDialogJob:false,
      radioId:"",
      currObj:{},
      isShowAdd:false,
      title: "添加",
      keyEntName:"",
      zyloading:false,
      curRow:{},
      currObjMx:{},
      equipmentList:[],
      count:0,
      isMxgraphVue2:false,
      widthVal:"100%",
      equipId:"",
      phaseList:[],
      isShowPhaseDialog:false,
      currPhaseObj:{},
      currPhaseObjTemp:{},
      phaseCount:0,
      isShowATO: false,
      isShowBTN: false,
      isShowDATA: false,
      isShowADM: false,
      isShowCHA: false,
      isShowCHA2: false,
      isShowCHA3: false,
      isShowIPT: false,
      isShowAGI: false,
      isShowTEM: false,
      isShowIFO: false,
      isShowOTM: false,
      isShowEXC: false,
      isShowREC: false,
      isShowTRS: false,
      isShowTRS2: false,
      isShowTEMWD1: false,
      isShowTEMWD2: false,
      isShowPRE: false,
      isShowJUMP: false,
      isreadOnly:false,
      stepObj:{},
      tdLoading:false,
      leftXml:"", //  左边列表xml数据
      isShowPhaseNameDialog:false,
      ruleFormPhase:{
        name:"",
        fid:"", //  设备类id
      },
      rulesPhase:{
        name:[{ required: true, message: '请输入phase名称', trigger: 'blur' },]
      },
      phaseData: {
        isActive: 0,
        isAuto: 1,
        delayTime: 0.0,
        mode: 0,
        checks: 0,
      },
      formulaCount:0,
      rightXmlCount:0,
      newDates:0
    }
  },
  watch: {
    screenWidth (val) {
      this.screenWidth = Number(val)
    },
  },
  mounted () {
    const that = this
    window.addEventListener('resize', function () {
      that.screenWidth = document.body.offsetWidth;
    })
    this.dragControllerDiv();
  },
  created(){  
    this.getTbrecipeList()
    this.getTrainList()
  },
  methods:{
    getMxgraphVue2Data(row){
      const item = this.tableData.find(item => item.jobDesc == row.value)
      this.currObjMx = item
      this.formulaFid = item.fid || item.fId
      this.rightXmlCount ++
      this.isMxgraphVue2 = true
    },
    hanfleDouble(row){
      console.log(row,232)
      const item = this.tableData.find(item => item.jobDesc == row.value) || {}
      this.currObjMx = item
      this.isShowDialogJob = true
      this.radioId = item.fid || item.fId
      this.$nextTick(() => {
        this.$refs.refTable.setCurrentRow(item)
      })
      
    },
    isShowDialogJobFn(obj){
      if(obj.fId){
        this.radioId = obj.fId
        this.handleEdit()
      }else{
        this.handleAdd()
      }
      
    },
    handleAdd () {
      if (!this.process) {
        this.$message.error('请选择配方');
        return
      }
      if (!this.isTrainVo) {
        this.$message.error('该配方没有分配设备组');
        return
      }
      this.title = "添加"
      this.ruleFormJob = {
        autoStart: 1,
        delayTime: 0,
        seqNo: 1,
      }

      try {
        this.$refs['ruleFormJob'].resetFields();
      } catch (e) { }
      this.isShowAdd = true

    },
    async handleEdit () {
      if (!this.isTrainVo) {
        this.$message.error('该配方没有分配设备组');
        return
      }
      // if (this.radioId == '') {
      //   this.$message.error('请选择修改的数据');
      //   return
      // }

      let res = await formula.operationFind(this.radioId)
      this.getEquipmentList()
      // let res1 = await configure.getEquipmentList()
      if (res.code == 200) {
        this.curRow = res.data
        this.ruleFormJob = {
          jobDesc: res.data.jobDesc,
          initSchedEntId: res.data.initSchedEntId,
          seqNo: res.data.seqNo,
          nextJob: res.data.nextJob,
          firstJob: res.data.firstJob,
          finalJob: res.data.finalJob,
          fid: res.data.fid,
          equipmentId: res.data.equipmentVo ? res.data.equipmentVo.fid : "",
          autoStart: res.data.autoStart,
          delayTime: res.data.delayTime ?? 0,
        }

        const index = this.classIdList.findIndex(item => item.fid == res.data.initSchedEntId)
        if (index == -1) {
          this.classIdList.push({
            fid: res.data.initSchedEntId,
            className: res.data.equipmentClassVo ? res.data.equipmentClassVo.className : ''
          })
        }

        // if (res1.code == 200) {
        // this.equipmentList = res1.data.rows.filter(item => {
        //   item.equipmentClassVo = item.equipmentClassVo ? item.equipmentClassVo : {}
        //   let trains = new Array()
        //   trains = item.trainVos.map(x => { return x.fid })
        //   return item.equipmentClassVo.fid == this.ruleFormJob.initSchedEntId && trains.includes(this.formData.trainId)
        // })
        // this.equipmentList = res1.data.rows
        // }
        this.title = "编辑"
        this.isShowAdd = true
      } else {
        this.$message.error('数据错误');
      }
    },
    async handleDel () {
      if (this.radioId === '') {
        this.$message.error('请选择要删除的数据');
        return
      }
      let res = await formula.operationFind(this.radioId)
      let that = this
      if (res.code == 200) {
        this.$customConfirm({
          content: "请确认是否删除作业" + res.data.jobDesc,
          onok () {
            formula.operationRemove(res.data.fid).then(res1 => {
              if (res1.code == 200) {
                that.radioId = ""
                that.getDataList()
                that.$message({ duration: 1000, type: 'success', message: '删除成功!' });
              }
            })
          }
        });
      }
    },
    //选择配方对话框
    handleFormula () {
      this.isShowDialog = true
    },
    handleClose () {
      this.isShowDialog = false
    },
    //配方查询
    handleSearch () {
      this.formulaPage.pageNum = 1
      this.formulaFid = ''
      this.getTbrecipeList()
    },
    //获取配方名称列表
    getTbrecipeList () {
      const param = {
        page: this.formulaPage.pageNum,
        size: this.formulaPage.pageSize,
        recipeName: this.ruleForm.keyword,
        recipeStatus: this.ruleForm.status,
        recipeType: 1,
        field: this.recipePager.field,
        order: this.recipePager.order,
        // isRecipeStatus:[1] //只能选择编辑的配方
      }
      this.formulaLoading = true
      scheduling.getTbrecipeList(param).then(res => {
        if (res.code == 200) {
          this.formulaList = res.data.rows
          this.formulaPage.total = res.data.total
        }
        this.formulaLoading = false
      })
    },
    handleSizeChange1 (val) {
      this.formulaPage.pageNum = 1
      this.formulaPage.pageSize = val
      this.getTbrecipeList()
    },
    handleCurrentChange1 (val) {
      this.formulaPage.pageNum = val
      this.getTbrecipeList()
    },
    //选择配方-确认
    handleCreate () {
      console.log(this.formData.trainId)
      if (!this.formulaFid) {
        this.$message.error('请选择配方');
        return
      }

      
      // this.$refs[formName].validate((valid) => {
      // if(valid){
      this.formData.trainId = ""
      this.isTrainVo = ""
      const item = this.formulaList.find(item => item.fid == this.formulaFid)
      this.recipeId = item.fid
      console.log(this.recipeId)
      this.isreadOnly = item.recipeStatus == 1 ? false : true //除了编辑状态 其余的都不能操作
      // const index = this.groupList.findIndex(el => el.fid == item.trainVo.fid)
      // if(index == -1){
      //     this.groupList.push({
      //         entName:item.trainVo.entName,
      //         fid:item.trainVo.fid,
      //     })
      // }
      this.formulaCount ++

      

      
      if (item.trainVo) {
        this.formData.trainId = item.trainVo.fid
        this.isTrainVo = item.trainVo.fid
      } else {
        this.formData.trainId = ""
        this.isTrainVo = ""
      }
      this.getDataList()
      this.getEquipmentClassList()



      
      // }
      // })
    },
    //选择配方处理
    rowFormulaClick (row) {
      this.formulaFid = row.fid
      this.$refs.formulaTable.setCurrentRow(row);
    },
    getEquipmentClassList () {
      configure.getEqpClsByTrainId(this.formData.trainId).then(res => {
        if (res.code == 200) {
          this.classIdList = res.data
        }
      }).catch(e => {

      })

    },
    //获取设备组列表
    getTrainList () {
      const param = {
        entName: this.pageGroud.keyword,
        page: this.pageGroud.pageNum,
        size: this.pageGroud.pageSize
      }
      configure.getTrainList(param).then(res => {
        if (res.code == 200) {
          this.groupList = [...this.groupList, ...res.data.rows]
          this.groupList = this.groupList.map(item => {
            return {
              entName: item.entName,
              fid: item.fid
            }
          })
        }
      })
    },
    remoteMethodGroup (keyword) {
      this.pageGroud.keyword = keyword.trim();
      this.pageGroud.pageNum = 1
      setTimeout(() => {
        this.groupList = []
        this.getTrainList()
      }, 200)
    },
    loadMoreGroupFun () {
      this.pageGroud.pageNum++
      this.getTrainList()
    },
    clearGroup () {
      this.pageGroud.keyword = ""
      this.pageGroud.pageNum = 1
      this.groupList = []
      this.getTrainList()
    },
    handleConfirmGroup () {
      if (!this.formulaFid) {
        this.$message.error('请选择配方');
        return
      }
      if (!this.formData.trainId) {
        this.$message.error('请选择设备组');
        return
      }
      const param = {
        fid: this.formulaFid,
        trainVo: {
          fid: this.formData.trainId
        }
      }
      this.loading = true
      addFormula.modifyTrain(param).then(res => {
        this.loading = false
        if (res.code == 200) {
          this.getDataList()
          this.formulaPage.pageNum = 1
          this.isTrainVo = this.formData.trainId
          this.formulaList = []
          this.getTbrecipeList()
          this.isShowDialog = false
          this.$message({ duration: 1000, type: 'success', message: '分配成功!' });
          this.getEquipmentClassList()
        } else {
          this.$message.error(res.msg);
        }
      }).catch(e => {
        this.isShowDialog = false
      })
    },
    //获取配方数据
    getDataList () {
      return new Promise((resolve, reject) => {
        let item = this.formulaList.find(item => item.fid == this.formulaFid)
        const param = {
          page: this.pager.pageNum,
          size: this.pager.pageSize,
          recipeId: this.recipeId,
          field: this.pager.field,
          order: this.pager.order,
        }
        this.tableLoading = true
        this.ruleFormLoading = true
        formula.operationList1(param).then(res => {
          this.tableLoading = false
          this.ruleFormLoading = false
          if (res.code == 200) {
            this.tableData = res.data.rows
            this.serialNum = []
            this.deviceList = []
            this.pager.total = res.data.total
            this.tableData.forEach((item, index) => {
              item.child = JSON.parse(JSON.stringify(this.child))
              this.serialNum.push(index + 1)

              this.deviceList.push({
                className: item.equipmentClassVo.className,
                fid: item.equipmentClassVo.fid
              })
            })
            console.log(this.tableData)
            try {
              this.process = " > " + item.recipeName + ' ' + (item.version == undefined ? '' : item.version) + " - " + this.queryStatus(item.recipeStatus)
            } catch (e) { }

            this.isShowDialog = false
            resolve(true)
          } else {
            this.tableLoading = false
            this.ruleFormLoading = false
            resolve(false)
          }
        }).catch(e => {
          this.tableLoading = false
          this.ruleFormLoading = false
           resolve(false)
        })
      })

      
    },
    handleSizeChange (val) {
      this.pager.pageNum = 1
      this.pager.pageSize = val
      this.getDataList()
    },
    handleCurrentChange (val) {
      this.pager.pageNum = val
      this.getDataList()
    },
    rowClick (row) {
      console.log(row,7777777777)
      this.radioId = row.fid;
      this.$refs.refTable.toggleRowExpansion(row)
      this.currObj = row
      
      this.$refs.refTable.setCurrentRow(row);
    },
    handleConfirmJob(){
      if(!this.radioId){
        this.$message.error('请选择作业');
        return
      }
      console.log(this.currObj)
      this.currObjMx = JSON.parse(JSON.stringify(this.currObj))
      this.count ++
      this.isShowDialogJob = false
    },
    handleCloseJobDialog(){
      this.isShowDialogJob = false
      
    },
    handleCloseJob () {
      this.isShowAdd = false
    },
    //下拉加载更多设备定义
    loadMoreItemClassFun () {
      this.pagerdev.pageNum++
      this.getEquipmentClassList()
    },
    //远程搜索设备定义
    remoteMethodItemClass (keyword) {
      this.pagerdev.keyword = keyword.trim();
      this.pagerdev.pageNum = 1
      setTimeout(() => {
        this.classIdList = []
        this.getEquipmentClassList()
      }, 200)
    },
    clearItemClass () {
      this.pagerdev.keyword = ""
      this.pagerdev.pageNum = 1
      this.classIdList = []
      this.getEquipmentClassList()
    },
    handleDeviceType () {
      this.ruleFormJob.equipmentId = ''
      this.getEquipmentList()
    },
    getEquipmentList () {
      const param = {
        entName: this.keyEntName,
        size: 99999999
      }
      configure.getEquipmentList(param).then(res => {
        if (res.code == 200) {
          let list = res.data.rows.filter(item => {
            item.equipmentClassVo = item.equipmentClassVo ? item.equipmentClassVo : {}
            let trains = new Array()
            if (item.trainVos != null) {
              trains = item.trainVos.map(x => { return x.fid })
              return item.equipmentClassVo.fid == this.ruleFormJob.initSchedEntId && trains.includes(this.formData.trainId)
            }


            // return item.equipmentClassVo.fid == this.ruleFormJob.initSchedEntId
          })
          // list.forEach(item => {
          //     if(item.trainVos){
          //         const index = item.trainVos.findIndex(el => el.fid == this.isTrainVo)
          //         if(index > -1){
          //             item.isTrainVo = true
          //         }
          //     }
          // })
          this.equipmentList = list
          // this.equipmentList = list.filter(item => {
          //     return item.isTrainVo
          // })
        }
      })
    },
    handleConfirm (formName) {
      //去掉 重复添加同一设备的校验
      // let ii = this.tableData.filter(ii => ii.equipmentVo.fid == this.ruleFormJob.equipmentId)
      // if (ii.length > 0) {
      //   this.$message({ duration: 1000, type: 'warn', message: '已经添加该设备!' })
      //   return
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleFormJob.recipeId = this.recipeId
          this.zyloading = true
          formula.operationAdd(this.ruleFormJob, this.title).then(res => {
            this.zyloading = false
            if (res.code == 200) {
              this.currObjMx = JSON.parse(JSON.stringify(res.data))
              this.radioId = res.data.fId || res.data.fid
              this.count ++
              this.isShowAdd = false
              this.$refs[formName].resetFields();
              this.getDataList()
            } else {
              this.$message.error(res.msg);
            }
          })
        }
      })
    },
    handleSelectedNode(data){
      this.currObjMx = data
    },
    async handlePhaseType(cell){
      console.log(this.currPhaseObj)
      this.currPhaseObj = cell
      this.ruleFormPhase.fid = cell.fid
      this.ruleFormPhase.name = cell.phaseName
      if(this.currObjMx.fId){
        this.currObjMx.fid = this.currObjMx.fId
      }
      
      let row = this.currObjMx
      this.radioId = row.fid;
      this.equipId = row.equipmentId
       console.log(this.equipId,'equipId')
      let param = {
        eqpClassId: row.equipmentClassVo ? row.equipmentClassVo.fid : ''
      }
      let res1 = await configure.getEqpClassPhaseLinkList(param)
      if (res1.code == 200) {
          const index = this.tableData.findIndex(item => item.fid == row.fid)
          console.log(this.tableData[index])
          var parse = JSON.parse(JSON.stringify(this.child));
          console.log(this.child)
          this.tableData[index].child = [];
          res1.data.rows.forEach((item) => {
            const value = {
              display: true,
              type: item.phaseDefineVo.type,
              text: item.phaseDefineVo.name,
              isShow: item.phaseDefineVo.sn,
              title: item.phaseDefineVo.sn,
              fid:item.fid
            }
            parse.forEach(item1 => {
              if (item.phaseDefineVo.sn == item1.title) {
                value.id = item1.id;
                value.itemType = item1.itemType
              }
            })
            this.tableData[index].child.push(value);
          })
          formula.findByOperationId(row.fid).then(res => {
            if (res.code == 200) {
              const index = this.tableData.findIndex(item => item.fid == row.fid)
              console.log(JSON.parse(JSON.stringify(this.tableData[index])))
              this.tableData[index].child.forEach(item => {
                this.$set(item, "stepVos", [])
                res.data.forEach(el => {
                  if (el.serialNo == item.id && item.text == el.phaseDesc) {
                    item.stepVos.push(el)
                  }
                })
              })

              console.info('handledetail', this.tableData)
             
              this.phaseList = this.tableData[index].child
              console.log(this.phaseList,"phaseList")
              this.isShowPhaseDialog = true

            } else {
              const index = this.tableData.findIndex(item => item.fid == row.fid)
              this.tableData[index].child.forEach(item => {
                this.$set(item, "stepVos", [])
              })
            }
          })
        }



    },
    rowClickPhase(row){
    //   console.log(row)
    //   this.phaseRadioId = row.fid || row.fId
    //   this.currPhaseObjTemp = row
    //   this.$refs.refPhaseTable.setCurrentRow(row);
    },
    // 双击弹窗
    doubleClickNode(cell){
      console.log("双击弹窗",cell)
      cell.currPhaseObj = cell.currPhaseObj || {}
      if(!cell.currPhaseObj.fid){
        this.$message.error('请选择phase1');
        return
      }
      let currRow = this.tableData.find(item => item.fid == this.radioId) //当前点击的作业
      this.equipId = currRow.equipmentId
      // if (currRow.phaseVos && currRow.phaseVos.length) { //如果已经新增过阶段信息

      // }
      this.stepObj = {mode: 0, texts: this.currPhaseObj.text, serialNo: this.currPhaseObj.id }
      console.log( this.currPhaseObj.isShow)
      this['isShow' + this.currPhaseObj.isShow.split("_")[1]] = true
    },
    handleConfirmPhase(){
      if(!this.ruleFormPhase.fid){
        this.$message.error('请选择phase');
        return
      }
      this.currPhaseObjTemp = this.phaseList.find(item => item.fid == this.ruleFormPhase.fid) || {}
      console.log(this.currPhaseObjTemp)
      this.currPhaseObjTemp.phaseName = this.ruleFormPhase.name
      this.currPhaseObj = JSON.parse(JSON.stringify(this.currPhaseObjTemp))
      this.phaseCount ++
      this.isShowPhaseDialog = false

      console.log(this.currPhaseObj,321)
      
      // this['isShow' + this.currPhaseObj.isShow.split("_")[1]] = true




    },
    handleClosePhaseDialog(){
      this.isShowPhaseDialog = false
      this.$refs['ruleFormPhase'].resetFields();
    },
    dragControllerDiv(){
        var resize = document.getElementsByClassName('resize');
        var left = document.getElementsByClassName('left');
        var mid = document.getElementsByClassName('mid');
        var box = document.getElementsByClassName('box');
        for (let i = 0; i < resize.length; i++) {
            // 鼠标按下事件
            resize[i].onmousedown = function (e) {
                //颜色改变提醒
                resize[i].style.background = '#818181';
                var startX = e.clientX;
                resize[i].left = resize[i].offsetLeft;
                // 鼠标拖动事件
                document.onmousemove = function (e) {
                    var endX = e.clientX;
                    var moveLen = resize[i].left + (endX - startX); // （endx-startx）=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
                    var maxT = box[i].clientWidth - resize[i].offsetWidth; // 容器宽度 - 左边区域的宽度 = 右边区域的宽度

                    if (moveLen < 32) moveLen = 32; // 左边区域的最小宽度为32px
                    if (moveLen > maxT - 150) moveLen = maxT - 150; //右边区域最小宽度为150px

                    resize[i].style.left = moveLen; // 设置左侧区域的宽度

                    for (let j = 0; j < left.length; j++) {
                        left[j].style.width = moveLen + 'px';
                        mid[j].style.width = (box[i].clientWidth - moveLen - 10) + 'px';
                    }
                };
                // 鼠标松开事件
                document.onmouseup = function (evt) {
                    //颜色恢复
                    resize[i].style.background = '#d6d6d6';
                    document.onmousemove = null;
                    document.onmouseup = null;
                    resize[i].releaseCapture && resize[i].releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
                };
                resize[i].setCapture && resize[i].setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
                return false;
            };
        }
    },
    
    handleequipmentId () {
      this.$forceUpdate()
    },
    uptionData (obj) {
      let index = this.tableData.findIndex(item => item.fid == obj.operationId)
      let index1 = this.tableData[index].child.findIndex(item => item.text == obj.text)
      let currPhase = this.tableData[index].child[index1].stepVos || []
   
      console.log(currPhase)
    },
    closePH (val) {
      this['isShow' + val] = false
    },
    queryStatus (status) {
      switch (status) {
        case 1:
          return "编辑"
        case 2:
          return this.$t('common.examine')
        case 3:
          return this.$t('common.approval')
        case 4:
          return "启用"
        case 5:
          return this.$t('common.abandoned')
        case 6:
          return "实验"
      }
    },
    table_index (index) {
      return (this.pager.pageNum - 1) * this.pager.pageSize + index
    },
    table_index1 (index) {
      return (this.formulaPage.pageNum - 1) * this.formulaPage.pageSize + index
    },
  }
}
</script>

<style scoped>
  .btngroup {
    margin-right: 20px;
  }
  .selectItem >>> .el-select {
    width: 100%;
  }
  .device_group_sel >>> .el-form-item--small.el-form-item{
    margin-bottom: 0;
  }
  .process {
    font-size: 14px;
    color: #666;
  }
  .selectClass >>> .el-select {
  width: 100%;
}
.isShowDialog >>> .el-dialog__body{
  padding: 0 20px;
}
.huabu{
  flex: 1;
}


  /* 拖拽相关样式 */
    /*包围div样式*/
    .box {
        width: 100%;
        height: 100%;
        overflow: hidden;
        position: relative;
    }
    /*左侧div样式*/
    .left {
        /* width: calc(32% - 10px);  */
        width:100%;
        height: 100%;
        background: #FFFFFF;
        float: left;
    }
    /*拖拽区div样式*/
    .resize {
      cursor: col-resize;
        float: left;
        background-color: #d6d6d6;
        border-radius: 5px;
        margin-top: 40vh;
        width: 10px;
        height: 50px;
        background-size: cover;
        background-position: center;
        /*z-index: 99999;*/
        font-size: 32px;
        color: white;
    }
    /*拖拽区鼠标悬停样式*/
    .resize:hover {
        color: #444444;
    }
    /*右侧div'样式*/
    .mid {
        float: left;
        width: 68%;   /*右侧初始化宽度*/
        height: 100%;
        background: #fff;
        box-shadow: -1px 4px 5px 3px rgba(0, 0, 0, 0.11);
    }
    .phaseType >>> .el-select{
      width: 100%;
    }
</style>
